import { defineConfig, build } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// @ts-ignore
import path from 'path'
import fsExtra from 'fs-extra/esm'
import fs from 'fs'

const __dirname = path.resolve();

import DefineOptions from 'unplugin-vue-define-options/vite'
import AutoImport from "unplugin-auto-import/vite"
const entryDir =  path.resolve(__dirname, 'packages')
const outDir =  path.resolve(__dirname, 'lib')

const baseConfig = defineConfig({
     configFile: false,
    publicDir: false,
    plugins: [
        vue(),
        vueJsx(),
        DefineOptions(),
        AutoImport ({
            imports: ["vue", "vue-router"], // 自动导入vue和vue-router相关函数
            dts: "auto-import.d.ts" // 生成 `auto-import.d.ts` 全局声明
        })
    ]
})

const rollupOptions = {
    external: ['vue', 'vue-router'],
    output: {
        globals: {
            vue: 'Vue'
        }
    }
}

// 全量打包
const buildAll = async () => {
    await build({
        ...baseConfig,
        build: {
            rollupOptions,
            lib: {
                entry: path.resolve(entryDir, 'index.ts'),
                name: 'yy-element-components',
                fileName: 'yy-element-components',
                formats: ['es', 'umd']
            },
            outDir: outDir
        }
    })
}
// 单组件打包
// name组件名称
const buildSingle = async name => {
    await build({
        ...baseConfig,
        build: {
            rollupOptions,
            lib: {
                entry: path.resolve(entryDir, name),
                name: 'index',
                fileName: 'index',
                formats: ['es', 'umd']
            },
            outDir:  path.resolve(outDir, name)
        }
    })
}
// 每个组件生成package.json
const createPackageJson = name => {
    const fileStr = `
        {
            "name": "${name}",
            "main": "index.umd.js",
            "module": "index.es.js",
            "style": "style.css"
        }
    `
    fsExtra.outputFile(
        path.resolve(outDir, `${name}/package.json`),
        fileStr,
        'utf-8'
    )
}

// 打包成库
const buildLib = async () => {
    await buildAll()

    // 获取组件名数组
    const components = fs.readdirSync(entryDir).filter(name => {
        const  componentDir = path.resolve(entryDir, name)
        const isDir = fs.lstatSync(componentDir).isDirectory()
        return isDir && fs.readdirSync(componentDir).includes('index.ts')
    })

    // 循环构建
    for (const name of components) {
        await buildSingle(name)
        createPackageJson(name)
    }
}
buildLib()
